<template>
  <div
    class="permit-box p20 bg-white console"
    v-loading.lock="fullscreenLoading"
    style="padding-bottom: 40px;"
  >
    <el-form ref="form" class="mt10">
      <el-row type="flex" justify="start">
        <el-col :span="3" v-if="permitIds.includes('manag_org_dept_add')">
          <el-form-item>
            <el-button class="theme-btn" @click="handleAddDept"
              >新增部门</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              class="theme-btn"
              @click="handleExpendAll"
              :icon="expandIcon"
              >{{ expandLabel }}</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tree
      ref="deptJob"
      node-key="id"
      :data="permitData"
      :props="defaultProps"
      class="home-permit-tree"
      :render-after-expand="false"
      :expand-on-click-node="false"
      :render-content="renderContent"
    ></el-tree>
    <DeptDialog
      :title="title"
      :loading="loading"
      @close="hanleClose"
      :deptForm="deptForm"
      :addDialog="addDialog"
      @update="handleUpdate"
      :editDialog="editDialog"
      :deptOldName="deptForm.name"
    ></DeptDialog>
    <JobDialog
      :title="title"
      :loading="loading"
      :jobForm="jobForm"
      @close="hanleClose"
      @update="handleUpdate"
      :addJobDialog="addJobDialog"
      :editJobDialog="editJobDialog"
    ></JobDialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import JobDialog from "./components/job_dialog";
import DeptDialog from "./components/dept_dialog";
import { getJobAndDept, deleteDept, deleteJob } from "@/apis/user";

export default {
  name: "Role_manage",
  data() {
    return {
      title: "",
      jobForm: {},
      deptForm: {},
      permitData: [],
      expendAll: false,
      addDialog: false,
      editDialog: false,
      addJobDialog: false,
      editJobDialog: false,
      expandLabel: "全部展开",
      fullscreenLoading: false,
      expandIcon: "el-icon-sort-down",
      defaultProps: {
        label: "name",
        children: "children",
        characterType: "characterType"
      }
    };
  },
  mounted() {
    this.openFullScreen();
    this.getDepts(1);
  },
  computed: {
    ...mapGetters(["pageSize", "pageNum", "queryStr", "permitIds", "loading"])
  },
  methods: {
    openFullScreen() {
      this.fullscreenLoading = true;
      setTimeout(() => {
        this.fullscreenLoading = false;
      }, 1500);
    },
    async getDepts(propertyId) {
      const { rows } = await getJobAndDept({ propertyId });
      const permitData = [];
      rows.forEach(item => {
        permitData.push({
          id: item.id,
          name: item.name,
          children: item.jobs ? item.jobs : []
        });
      });
      this.permitData = permitData;
    },
    handleExpendAll() {
      const actionrefs = this.$refs["deptJob"];
      const childNodes = actionrefs.root.childNodes;
      this.expendAll = !this.expendAll;
      childNodes.forEach(item => {
        if (this.expendAll) {
          item.expanded = true;
          this.expandLabel = "全部展开";
          this.expandIcon = "el-icon-sort-down";
        } else {
          item.expanded = false;
          this.expandLabel = "全部收起";
          this.expandIcon = "el-icon-sort-up";
        }
      });
    },
    handleAddDept() {
      this.title = "新增部门";
      this.addDialog = !this.addDialog;
    },
    handleEditDept(item) {
      this.deptForm = item;
      this.title = "部门更名";
      this.editDialog = !this.editDialog;
    },
    hanleClose() {
      this.addDialog = false;
      this.editDialog = false;
      this.addJobDialog = false;
      this.editJobDialog = false;
      this.$store.dispatch("load/setLoading", false);
    },
    handleUpdate() {
      this.getDepts(1);
    },
    handleAddJob(data) {
      this.title = "新增岗位";
      this.jobForm = {
        deptId: data.id,
        deptName: data.name
      };
      this.addJobDialog = !this.addJobDialog;
    },
    handleEditJob(parentName, data) {
      this.title = "编辑岗位";
      this.jobForm = {
        jobId: data.id,
        jobName: data.name,
        deptName: parentName,
        characterType: data.characterType
      };
      this.editJobDialog = !this.editJobDialog;
    },
    handleDeleteConfirm(data) {
      data.children
        ? this.handleDelete("dept", data)
        : this.handleDelete("job", data);
    },
    handleDelete(type, data) {
      this.$confirm("此操作将删除该条, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$store.dispatch("load/setLoading", true);
          if (type === "dept") {
            // deleteDept({ departmentId: data.id }).then(res => {
            //   if (res && res.code === "200") {
            //     this.$notify({
            //       title: res.msg,
            //       type: "success"
            //     });
            //     this.$store.dispatch("load/setLoading", false);
            //     this.handleUpdate();
            //   }
            // });
            this.$notify({
              title: "操作成功！",
              type: "success"
            });
            this.$store.dispatch("load/setLoading", false);
            this.handleUpdate();
          } else {
            // deleteJob({ jobId: data.id }).then(res => {
            //   if (res && res.code === "200") {
            //     this.$notify({
            //       title: res.msg,
            //       type: "success"
            //     });
            //     this.$store.dispatch("load/setLoading", false);
            //     this.handleUpdate();
            //   }
            // });
            this.$notify({
              title: "操作成功！",
              type: "success"
            });
            this.$store.dispatch("load/setLoading", false);
            this.handleUpdate();
          }
        })
        .catch(() => {
          this.$message("已取消删除");
        });
    },
    changeStyle() {
      const permitMenu = document.querySelectorAll(".permit-menu");
      permitMenu.forEach(item => {
        const index = item.getAttribute("index") - 1;
        index >= 0 && (item.parentNode.style.marginLeft = `${index * 38}px`);
      });
    },
    renderContent(h, { node, data, store }) {
      this.$nextTick(this.changeStyle);
      const isDept = node.level && node.level === 1;

      return (
        <span class="permit-menu" index={node.level}>
          <span>
            <span class="ml10">{node.label}</span>
          </span>
          <span class="operation">
            <el-button
              v-show={isDept && this.permitIds.includes("manag_org_job_add")}
              class="theme-btn"
              on-click={() => this.handleAddJob(data)}
            >
              新增岗位
            </el-button>
            <el-button
              v-show={
                isDept && this.permitIds.includes("manag_org_dept_update")
              }
              on-click={() => this.handleEditDept(data)}
            >
              部门更名
            </el-button>
            <el-button
              v-show={!isDept && this.permitIds.includes("manag_org_update")}
              on-click={() => this.handleEditJob(node.parent.label, data)}
            >
              编辑权限
            </el-button>
            <el-button
              class="ml10"
              v-loading={this.loading}
              on-click={() => this.handleDeleteConfirm(data)}
              v-show={this.permitIds.includes("manag_org_delete")}
            >
              删除
            </el-button>
          </span>
        </span>
      );
    }
  },
  components: {
    JobDialog,
    DeptDialog
  }
};
</script>

<style scoped lang="less"></style>
